<template>
  <el-container style="height: 100vh;">
    <el-aside width="200px">
      <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-demo"
          router
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b"
      >
        <el-menu-item v-for="item in menuList" :key="item.path" :index="item.path">
          {{ item.label }}
        </el-menu-item>
      </el-menu>
    </el-aside>
    <el-container>
      <el-header style="background:#fff;line-height:60px;font-size:20px;padding:0 20px;">
        <div class="header-container">
          <div class="header-title">酒店管理系统</div>
          <div class="header-right">
            <span class="username" v-if="userInfoStore.userInfo">{{ userInfoStore.userInfo.userId }}</span>
            <el-dropdown trigger="click">
              <span class="user-dropdown">
                个人中心 <el-icon><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goToProfile">个人信息</el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      <el-main style="background:#f5f5f5;">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>
<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { computed } from 'vue'
import { useUserInfoStore } from '@/stores/userInfo'
import { logout } from '@/api/user'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userInfoStore = useUserInfoStore()
const activeMenu = computed(() => route.path)

// 跳转到个人信息页面
const goToProfile = () => {
  router.push('/profile')
}

// 退出登录
const handleLogout = () => {
  logout().then((res: any) => {
    const result = res.data
    if (result.code === 200) {
      // 清除用户信息
      userInfoStore.clearUserInfo()
      ElMessage.success('退出登录成功')
      // 跳转到登录页
      router.push('/login')
    }
  }).catch((error) => {
    console.error('退出登录错误:', error)
    // 即使API调用失败，也清除本地用户信息并跳转
    userInfoStore.clearUserInfo()
    router.push('/login')
  })
}

// 菜单项及其对应的权限
const menuConfig = [
  { 
    path: '/user', 
    label: '用户管理', 
    requiredPermissions: ['admin_manage'] 
  },
  { 
    path: '/hotel', 
    label: '酒店管理', 
    requiredPermissions: ['view_hotel', 'create_hotel', 'update_hotel'] 
  },
  { 
    path: '/room', 
    label: '房间管理', 
    requiredPermissions: ['view_room', 'create_room', 'update_room'] 
  },
  { 
    path: '/order', 
    label: '订单管理', 
    requiredPermissions: ['create_order', 'pay_order', 'cancel_order'] 
  },
  { 
    path: '/review', 
    label: '评论管理', 
    requiredPermissions: ['view_review', 'create_review'] 
  }
]

// 检查用户是否有特定权限的函数
const hasPermission = (permissionName: string) => {
  const permissions = userInfoStore.userInfo?.permissions || [];
  
  // 检查权限数组中是否有匹配的权限
  return permissions.some((permission: any) => {
    // 如果permission是字符串，直接比较
    if (typeof permission === 'string') {
      return permission === permissionName;
    }
    
    // 尝试从对象中获取权限名称 - 考虑各种可能的属性名
    const permissionCode = permission.name || 
                          permission.permission_name || 
                          permission.permissionName || 
                          permission.code ||
                          '';
    
    console.log(`比较权限: ${permissionCode} 与 ${permissionName}`);
    
    // 如果是完全匹配
    if (permissionCode === permissionName) {
      return true;
    }
    
    // 如果数据库存储的是ID而不是权限名称，需要额外判断
    if (permission.id) {
      // 根据数据库中的权限ID表映射关系判断
      const permissionIdMap = {
        1: 'view_hotel',
        2: 'view_room',
        3: 'view_review',
        4: 'create_review',
        5: 'create_order',
        6: 'pay_order',
        7: 'cancel_order',
        8: 'create_hotel',
        9: 'create_room',
        10: 'update_room',
        11: 'update_hotel',
        12: 'admin_manage'
      };
      
      return permissionIdMap[permission.id] === permissionName;
    }
    
    return false;
  });
  }
  
// 根据用户权限动态过滤菜单
const menuList = computed(() => {
  const permissions = userInfoStore.userInfo?.permissions || [];
  console.log('用户信息:', userInfoStore.userInfo);
  console.log('权限信息:', permissions);
  
  // 如果用户有admin_manage权限，显示所有菜单
  if (hasPermission('admin_manage')) {
    console.log('用户有管理员权限，显示所有菜单');
    return menuConfig;
  }
  
  // 过滤菜单 - 只要有菜单中任一所需权限即可显示该菜单
  return menuConfig.filter(menu => {
    return menu.requiredPermissions.some(permission => hasPermission(permission));
  });
})
</script>
<style scoped>
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}
.header-title {
  font-weight: bold;
}
.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}
.username {
  font-size: 14px;
  color: #606266;
}
.user-dropdown {
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #409EFF;
}
</style>
